package com.tianqu.tms.core.util.car;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.util.HttpUtil;
import com.tianqu.tms.core.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class CarInformationApi {
	private static String URL = "http://api.che300.com/service/identifyModelByVIN";
	private static String token = "88f8b200cf65ad7646ebbdff671ea51d";
	private static HttpUtil HTTP = new HttpUtil();
	private static Logger LOGGER = Logger.getLogger(CarInformationApi.class);// log
	
	public static IdentifyModelByVinBean getIdentifyModelByVin(String vin) {
		return getIdentifyModelByVin(token,vin);
	}

	public static IdentifyModelByVinBean getIdentifyModelByVin(String token,String vin) {
		IdentifyModelByVinBean bean = new IdentifyModelByVinBean();
		try {
			//
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("token", token);
			map.put("vin", vin);
			String r = HTTP.doGet(URL, map);
			//
			JSONObject json = JSONObject.fromObject(r);
			String status = json.getString("status");
			if(!StringUtil.isNullOrBlank(status) && status.equals("1")){
				JSONArray array = json.getJSONArray("modelInfo");
				List<Map<String, String>> list =  (List<Map<String, String>>)JSONArray.toCollection(array, Map.class);
				Map<String, String> hashMap = new HashMap<String, String>();
				if(list!=null && list.size()>0) hashMap = list.get(0);

				bean.setStatus(status);
				bean.setSeriesName(parse2String(hashMap.get("series_name")));
				bean.setSeriesId(parse2String(hashMap.get("series_id")));
				bean.setModelYear(parse2String(hashMap.get("model_year")));
				bean.setModelName(parse2String(hashMap.get("model_name")));
				bean.setModelPrice(parse2String(hashMap.get("model_price")));
				bean.setModelLiter(parse2String(hashMap.get("model_liter")));
				bean.setModelId(parse2String(hashMap.get("model_id")));
				bean.setModelGear(parse2String(hashMap.get("model_gear")));
				bean.setModelEmissionStangard(parse2String(hashMap.get("model_emission_standard")));
				bean.setMinRegYear(parse2String(hashMap.get("min_reg_year")));
				bean.setMaxRegYear(parse2String(hashMap.get("max_reg_year")));
				bean.setExtModelId(parse2String(hashMap.get("ext_model_id")));
				bean.setBrandName(parse2String(hashMap.get("brand_name")));
				bean.setBrandId(parse2String(hashMap.get("brand_id")));
			}
		} catch (Exception e) {
			LOGGER.error(e);
		}
		return bean;
	}

	private static String parse2String(Object obj){
		try {
			if(obj instanceof String) return (String)obj;
			else if (obj instanceof Integer)  return obj.toString();
			else if (obj instanceof Double)  return obj.toString();
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error(e);
			return "";
		}
		return "";
	}
}
